<?php
/**
 * Created by IntelliJ IDEA.
 * User: ftavora
 * Date: 03/02/2015
 * Time: 11:27
 */

namespace CAI\HistoricoBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use CAI\HistoricoBundle\Entity\Arbitro;
use CAI\HistoricoBundle\Entity\Tecnico;
use CAI\HistoricoBundle\Form\Type\PersonaType;

use \Doctrine\DBAL\DBALException;

class AjaxPersonasController extends AjaxBaseController
{
    public function ajaxGuardarArbitroAction(Request $request)
    {
        if($request->isXmlHttpRequest()) {

            $arbitro = new Arbitro();
            $form = $this->createForm(new PersonaType(), $arbitro);
            $form->handleRequest($request);

            $a = $form->getData();

            $f = $this->parseDateToDatabase($request->request->get('fechaNac'));	//fechaNac

            $a->setPersonasFechaNac($f);

            $id = $this->getDoctrine()->getRepository('CAIHistoricoBundle:Persona');
            $query = $id->createQueryBuilder('p')
                ->select('p, MAX(p.personas_id) AS max_id');
            $maxId = $query->getQuery()->getResult();

            $a->setPersonasId($maxId[0]['max_id'] +1);

            $em = $this->getDoctrine()->getManager();
            $em->persist($a);
            $em->flush();

            return new Response("Hey Ho!");
        }else{
            return new Response("Puta!");
        }
    }

    public function ajaxGuardarTecnicoAction(Request $request)
    {
        if($request->isXmlHttpRequest()) {

            $tecnico = new Tecnico();
            $form = $this->createForm(new PersonaType(), $tecnico);
            $form->handleRequest($request);

            $t = $form->getData();

            $f = $this->parseDateToDatabase($request->request->get('fechaNac'));	//fechaNac

            $t->setPersonasFechaNac($f);

            //todo validar si es true (1) y deshabilitar, si es false (0) no hacer nada, solo guardar
            $t->setTecnicosActivo($request->request->get('chkTecnicoActivo'));

            $id = $this->getDoctrine()->getRepository('CAIHistoricoBundle:Persona');
            $query = $id->createQueryBuilder('p')
                ->select('p, MAX(p.personas_id) AS max_id');
            $maxId = $query->getQuery()->getResult();

            $t->setPersonasId($maxId[0]['max_id'] +1);

            $em = $this->getDoctrine()->getManager();
            $em->persist($t);
            $em->flush();

            return new Response("Hey Ho!");
        }else{
            return new Response("Puta!");
        }
    }

} 